/**
 * Created by Ysssssss on 20/7/3.
 */

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    var dataURL = canvas.toDataURL("image/" + ext);
    return dataURL;
}

const downloadImg = (imgUrl, name) => {
    var image = new Image();
    image.crossOrigin = '';
    image.src = imgUrl;
    image.onload = function () {
        var base64 = getBase64Image(image);
        var aLink = document.createElement('a');
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);
        aLink.download = name;
        aLink.href = base64;
        aLink.dispatchEvent(evt);
    }
}

export default downloadImg